package com.example.librarymanagementsystembackend.bookmanagement.controller;

import com.example.librarymanagementsystembackend.bookmanagement.entity.BookCategory;
import com.example.librarymanagementsystembackend.bookmanagement.entity.BookInformation;
import com.example.librarymanagementsystembackend.bookmanagement.service.BookService;
import com.example.librarymanagementsystembackend.utils.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

/**
 * 图书管理模块 控制器
 */
@RestController
@RequestMapping("/book")
public class BookController {

    @Autowired
    private BookService bookService;
    @Autowired
    private FileUtils fileUtils;

    /**
     * 获取图书类别
     */
    @GetMapping("/category")
    public List<BookCategory> getBookCategories() {
        return bookService.getBookCategories();
    }

    /**
     * 添加图书
     */
    @PostMapping
    public String addBook(@RequestBody BookInformation bookInformation) {
        try {
            bookService.addBook(bookInformation);
            return "图书添加成功";
        } catch (InvalidRequestException e) {
            throw new InvalidRequestException("图书添加失败（" + e.getMessage() + "）");
        }
    }

    @Operation(summary = "获取图书封面", description = "根据图书ID返回封面图片流")
    @ApiResponses({
            @ApiResponse(
                    responseCode = "200",
                    description = "封面图片流",
                    content = {
                            @Content(mediaType = "image/png",
                                    schema = @Schema(type = "string", format = "binary")),
                            @Content(mediaType = "image/jpeg",
                                    schema = @Schema(type = "string", format = "binary"))
                    }
            ),
            @ApiResponse(
                    responseCode = "404",
                    description = "图书不存在或封面未找到"
            ),
            @ApiResponse(
                    responseCode = "500",
                    description = "服务器内部错误"
            )
    })
    @GetMapping("/{id:\\d+}/cover")
    public ResponseEntity getBookCover(@PathVariable int id) throws IOException {
        String path = bookService.getBookById(id).getCoverUrl();
        Resource resource = fileUtils.getFile(path);
        // 检查文件是否存在
        if (!resource.exists()) {
            throw new InvalidRequestException(404, "文件不存在");
        }
        // 判断文件类型
        String mimeType = Files.probeContentType(Paths.get(path));
        if (mimeType == null) {
            mimeType = "application/octet-stream";
        }
        // 设置响应头
        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(mimeType))
                .body(resource);
    }

    @PostMapping(value="/{id:\\d+}/cover", consumes=MediaType.MULTIPART_FORM_DATA_VALUE)
    public String addBookCover(
            @PathVariable int id,
            @RequestPart("file") MultipartFile file) {
        String path = fileUtils.addFile("/img/bookCover", file);
        if (path == null) {
            throw new InvalidRequestException(404, "文件不存在");
        }
        BookInformation book = bookService.getBookById(id);
        book.setCoverUrl(path);
        bookService.updateBook(book);
        return "成功上传文件";
    }

    /**
     * 获取书本 通过 ID
     */
    @GetMapping("/{id:\\d+}")
    public BookInformation getBookById(@PathVariable int id) {
        return bookService.getBookById(id);
    }

    /**
     * 删除图书 通过 ID
     */
    @DeleteMapping("/{id:\\d+}")
    public String deleteBookById(@PathVariable int id) {
        try {
            bookService.deleteBookById(id);
            return "图书删除成功";
        } catch (InvalidRequestException e) {
            throw new InvalidRequestException("图书删除失败（" + e.getMessage() + "）");
        }
    }

    /**
     * 更新图书 通过 图书类
     */
    @PutMapping
    public String updateBook(@RequestBody BookInformation bookInformation) {
        try {
            bookService.updateBook(bookInformation);
            return "图书信息更新成功";
        } catch (InvalidRequestException e) {
            throw new InvalidRequestException("图书信息更新失败（" + e.getMessage() + "）");
        }
    }

    @GetMapping
    public List<BookInformation> queryBooks(@RequestParam int pageSize, @RequestParam int pageIndex) {
        try {
            return bookService.queryBooks(pageSize, pageIndex);
        } catch (InvalidRequestException e) {
            throw new InvalidRequestException("图书分页查询失败（" + e.getMessage() + "）");
        }
    }
}
